using System;
using System.Collections;
using System.Collections.Generic;
using ICSharpCode.TextEditor.Document;

namespace ICSharpCode.TextEditor.Util
{
    public class ThreadSafeList<T> : IEnumerable, IDisposable where T : DrawLine
    {
        private static readonly object lockToken = new object();

        private List<T> collection = new List<T>();

        public object SynchRoot => lockToken;

        public T this[int index]
        {
            get
            {
                lock (lockToken)
                {
                    return collection[index];
                }
            }
        }

        public void Dispose()
        {
            lock (lockToken)
            {
                collection.Clear();
                GC.Collect(1, GCCollectionMode.Optimized);
            }
        }

        public IEnumerator GetEnumerator()
        {
            lock (lockToken)
            {
                return collection.GetEnumerator();
            }
        }

        public ThreadSafeList<T> CloneToList<S>() where S : T, new()
        {
            lock (lockToken)
            {
                ThreadSafeList<T> threadSafeList = new ThreadSafeList<T>();
                foreach (T item in collection)
                {
                    threadSafeList.Add((T)new S
                    {
                        StartLocation = item.StartLocation,
                        EndLocation = item.EndLocation,
                        StartPoint = item.StartPoint,
                        EndPoint = item.EndPoint
                    });
                }
                return threadSafeList;
            }
        }

        public void Add(T item)
        {
            lock (lockToken)
            {
                collection.Add(item);
            }
        }

        public void Clear()
        {
            lock (lockToken)
            {
                collection.Clear();
            }
        }
    }
}
